"""
JWT工具模块
"""
from datetime import datetime, timedelta
from jose import jwt, JWTError
from typing import Optional, Dict

# JWT密钥（生产环境应放在环境变量中）
SECRET_KEY = "your-secret-key-change-in-production-123456789"
ALGORITHM = "HS256"

# Token过期时间
ACCESS_TOKEN_EXPIRE_HOURS = 2  # 2小时
REFRESH_TOKEN_EXPIRE_DAYS = 7  # 7天


def create_access_token(data: Dict, expires_delta: Optional[timedelta] = None) -> str:
    """
    创建访问令牌
    
    Args:
        data: 要编码的数据（如user_id, username等）
        expires_delta: 过期时间增量
        
    Returns:
        JWT token字符串
    """
    to_encode = data.copy()
    
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(hours=ACCESS_TOKEN_EXPIRE_HOURS)
    
    to_encode.update({"exp": expire, "type": "access"})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def create_refresh_token(data: Dict) -> str:
    """
    创建刷新令牌（有效期更长）
    
    Args:
        data: 要编码的数据
        
    Returns:
        JWT refresh token字符串
    """
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
    to_encode.update({"exp": expire, "type": "refresh"})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def verify_token(token: str, token_type: str = "access") -> Optional[Dict]:
    """
    验证并解码token
    
    Args:
        token: JWT token字符串
        token_type: token类型（access或refresh）
        
    Returns:
        解码后的数据，如果无效返回None
    """
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        
        # 检查token类型
        if payload.get("type") != token_type:
            return None
            
        # 检查是否过期
        exp = payload.get("exp")
        if exp and datetime.fromtimestamp(exp) < datetime.utcnow():
            return None
            
        return payload
    except JWTError:
        return None


def get_current_user(token: str) -> Optional[int]:
    """
    从token中获取当前用户ID
    
    Args:
        token: JWT token
        
    Returns:
        用户ID，如果token无效返回None
    """
    payload = verify_token(token)
    if payload:
        return payload.get("user_id")
    return None

